<!--
*  2021-03-15
*  登录
-->
<template>
  <div id="app" class="login">
    <!-- 头部导航 -->
    <van-nav-bar
      title="登 录"
      ref="header"
      left-arrow
      left-text="清除打印机"
      @click-left="onClickLeft"
      right-text="选择打印机"
      @click-right="onClickPrint"
    >
    </van-nav-bar>
    <!-- logo -->
    <div class="login-logo"></div>
    <!-- form -->
    <van-form @submit="onSubmit">
      <van-field
        v-model="no"
        name="no"
        label="工号"
        placeholder="请输入工号"
        clearable
        type="tel"
        :rules="[{ required: true, message: '请输入工号' }]"
      />
      <van-field
        v-model="pwd"
        name="pwd"
        label="密码"
        :type="type"
        placeholder="请输入密码"
        clearable
        :rules="[{ required: true, message: '请输入密码' }]"
      >
        <template #right-icon>
          <van-icon name="closed-eye" @click="onClosed" />
        </template>
      </van-field>

<!--      <tesseract-ocr @result="resultFn"></tesseract-ocr>-->

      <div style="margin: 30px 0">
        <van-button block type="info" native-type="submit" class="bgColor">登 录</van-button>
        <p v-if="address" style="width: 100%;display: flex;justify-content: center;font-size: 12px;line-height: 40px;">
          <span>当前打印机：</span>
          <span style="color: #e4393c">{{
            printObj.name || printObj.address
          }}</span>
        </p>
      </div>
    </van-form>

<!--    <div><van-button @click="openDemoFn">打开demo</van-button></div>-->

    <div style="margin-bottom:2vh; flex: 1 1 auto;display: flex;flex-flow: row wrap;align-items: flex-end;">
      <div>
        <span style="padding-bottom: 25px;font-size: small">v3.1.28</span>
      </div>
      <van-button style="margin-left:1vw;height: 2vh" size="mini" type="danger" @click="clearCacheFn">更新</van-button>
    </div>

    <!-- 连接蓝牙 -->
    <van-dialog
      v-model="show"
      title="选择打印机"
      show-cancel-button
      confirmButtonText="确认"
      cancelButtonText="取消"
      @confirm="onClickConfirm"
    >
      <van-radio-group v-model="address">
        <van-cell
          v-for="(scan, index) in scanList"
          :key="index"
          :title="scan.name ? scan.name : scan.address"
          clickable
          @click="onClickRadio(scan)"
        >
          <template #right-icon>
            <van-radio :name="scan.address" />
          </template>
        </van-cell>
      </van-radio-group>
    </van-dialog>
  </div>
</template>

<script>
// import { getLogin } from "@/api/login";
import {randomStr, closeApp, openWin} from "@/utils/index";
import {
  getLoginNo,
  getLoginPwd,
  setMacAddress,
  getMacAddress,
  removeMacAddress,
} from "@/utils/auth";
// import TesseractOcr from "@/components/tesseract-ocr";

export default {
  name: "Login",
  components: {},
  data() {
    return {
      no: "",
      pwd: "",
      captcha: "",
      type: "password",
      show: false,
      scanList: [],
      address: "",
      values: {},
      isShow: false,
      isFlag: false,
      name: "",
      printObj: {},
    };
  },
  created() {
    if (getMacAddress()) {
      this.address = getMacAddress().address;
      this.printObj = {
        name: getMacAddress().name || "",
        address: getMacAddress().address,
      };
    }
  },
  mounted() {
    const that = this;
    if (process.env.NODE_ENV === "production") {
      this.$nextTick(() => {
        that.initFn(that);
      });
    } else {
      window.apiready = function () {
        that.initFn(that);
      };
    }
  },
  methods: {
    /*openDemoFn() {
      openWin("demo");
    },*/

    getMacAddress,

    //更新清理
    clearCacheFn() {
      const that = this;
      window.api.clearCache(() => {
        that.$toast.success("更新成功");
        window.api.rebootApp();
      });
    },

    //初始化
    initFn(that) {
      that.no = getLoginNo() ? getLoginNo() : "";
      that.pwd = getLoginPwd() ? getLoginPwd() : "";
      // 监听页面消失的时候，关掉页面就可以了
      window.api.addEventListener({
        name: "viewdisappear",
      }, function () {
        window.api.closeWin();
      });
      closeApp();
    },

    // 清除打印机
    onClickLeft() {
      this.address = ''
      removeMacAddress()
      this.$toast.success('清除成功')
    },
    // 密码切换
    onClosed() {
      this.type = this.type === "password" ? "text" : "password";
    },
    // 登录
    onSubmit(values) {
      this.values = values;
      this.captcha = randomStr();
      this.values.captcha = this.captcha;
      this.values.platform = 3;
      this.$store.dispatch("user/login", this.values);
    },
    // 打印机弹窗
    onClickPrint() {
      this.$toast({
        type: "loading",
        message: "设备搜索中",
        duration: 0,
      });
      this.scanList = [{
        name: 'PDA',
        address: "00:11:22:33:44:55"
      }];
      this.isEnabledBluetooth();
    },
    // 连接
    onClickConfirm() {
      setMacAddress(this.printObj);
      this.show = false;
    },
    // 选择打印机
    onClickRadio(data) {
      this.address = data.address;
      this.printObj = {
        name: data.name || data.address,
        address: data.address,
      };
    },
    // 判断蓝牙是否打开
    isEnabledBluetooth() {
      const that = this;
      window.api
        .require("cxgBluetoothBase")
        .isEnabledBluetooth({}, (ret, err) => {
          if (!err) {
            if (ret.state) {
              // 已打开
              that.getScan();
            } else {
              that.openBluetooth();
            }
          } else {
            that.$toast.fail("code: " + err.code + " msg: " + err.msg);
          }
        });
    },
    // 打开蓝牙
    openBluetooth() {
      const that = this;
      window.api
        .require("cxgBluetoothBase")
        .openBluetooth({}, function (ret, err) {
          if (!err) {
            if (ret.state) {
              // 已打开
              that.getScan();
            }
          } else {
            that.listenBluetoothStatus();
          }
        });
    },
    // 监听蓝牙连接状态
    listenBluetoothStatus() {
      const that = this;
      window.api
        .require("cxgBluetoothBase")
        .listenBluetoothStatus({}, function (ret, err) {
          if (!err) {
            if (ret.status === "STATE_ON") {
              that.getScan();
            }
          } else {
            that.$toast.fail("code: " + err.code + " msg: " + err.msg);
          }
        });
    },
    // 搜索周边设备
    getScan() {
      const that = this;
      window.api.require("cxgBluetoothBase").scan({}, function (ret, err) {
        if (!err) {
          if (ret.data == "ACTION_DISCOVERY_FINISHED") {
            that.$toast.clear();
            if (that.scanList.length === 0) {
              that.$toast({
                type: "fail",
                message: "附近暂无打印机，直接登录",
                onClose: () => {
                  // 登录
                  that.onClickConfirm();
                },
              });
            } else {
              // that.address = that.scanList[0].address;
              // that.printObj = {
              //   name: that.scanList[0].name || "",
              //   address: that.scanList[0].address,
              // };
              that.show = true;
            }
          } else {
            if (that.scanList.length === 0) {
              if (
                ret.data &&
                JSON.stringify(ret.data) != "{}" &&
                ret.data != true
              ) {
                that.scanList.push({
                  name: ret.data.name || "",
                  address: ret.data.address,
                });
              }
            } else {
              if (
                ret.data &&
                JSON.stringify(ret.data) != "{}" &&
                ret.data != true
              ) {
                let index = that.scanList.findIndex(
                  (item) => item.address === ret.data.address
                );
                if (index === -1) {
                  that.scanList.push({
                    name: ret.data.name || "",
                    address: ret.data.address,
                  });
                }
              }
            }
          }
        } else {
          console.log("code: " + err.code + " msg: " + err.msg);
        }
      });
    },

    /*resultFn(result) {
      console.log(result);
    }*/
  },
};
</script>

<style lang="scss">
.login {
  display: flex;
  flex-direction: column;
  align-items: center;
  // // padding-top: 22px;
  .login-logo {
    width: 150px;
    height: 100px;
    @include bg-image("./../../assets/img/logo");
    margin: 50px 0;
  }
  .van-form {
    width: 100%;
    padding: 0 16px;
    .van-cell {
      .van-field__right-icon {
        margin-left: 15px;
      }
    }
    .van-field__label {
      width: 50px !important;
      font-family: PingFangSC-Regular;
      color: #cccccc;
      span {
        color: #333;
      }
    }
  }

  .bgColor {
    @include btnStyle;
  }

  .van-dialog__content {
    max-height: 400px;
    overflow: auto;
  }
}
</style>
